/*
 * Copyright (c) 2014-2019 2019 xmars All Rights Reserved.
 * ProjectName: xmars
 * FileName: IpUtil.java
 * Author: pipi
 * Date: 19-1-3 下午6:10
 * Version: 1.0
 * LastModified: 18-12-29 下午1:22
 */

package com.topsun.framework.common.core.util;

import cn.hutool.core.collection.CollUtil;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * IP工具类
 */
@Slf4j
public class IpUtil {

    private IpUtil() {
    }

    /**
     * 是否有效ip地址
     *
     * @param ip
     * @return
     */
    public static boolean isIp(String ip) {
        if (StringUtils.isEmpty(ip)) {
            return false;
        }
        return RegexUtil.checkIpAddress(ip);
    }

    /**
     * 比较ip地址大小
     *
     * @param ip1
     * @param ip2
     * @return
     */
    public static int compare(String ip1, String ip2) {
        Assert.state(isIp(ip1), "ip1不是有效ip地址");
        Assert.state(isIp(ip2), "ip2不是有效ip地址");
        List<String> ipList1 = Lists.newArrayList(Splitter.on(".").trimResults().omitEmptyStrings().split(ip1));
        List<String> ipList2 = Lists.newArrayList(Splitter.on(".").trimResults().omitEmptyStrings().split(ip2));
        int result = 0;
        for (int i = 0; i < ipList1.size(); i++) {
            result = Integer.compare(Integer.parseInt(ipList1.get(i)), Integer.parseInt(ipList2.get(i)));
            if (result != 0) {
                return result;
            }
        }
        return result;
    }

    /**
     * 获取本机ip
     * @return
     */
    public static String getLoaclIp() {

        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration<InetAddress> inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = inetAddrs.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址，就是它了
                            return inetAddr.getHostAddress();
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress.getHostAddress();
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            return jdkSuppliedAddress.getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 计算ip网络段
     * @param ip
     * @param maskBit
     * @return
     */
    public static String caculateNetworkSegment(String ip, Integer maskBit) {

        String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
        // 判断ip地址是否与正则表达式匹配
        if (!ip.matches(regex)) {
            log.error("IP地址不合规范, ip = {}", ip);
            return null;
        }
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(String.valueOf(maskBit));
        if (!m.matches() || maskBit<=0 || maskBit >32){
            log.error("子网掩码位不合规范");
            return null;
        }
        List<String> otherBits = new ArrayList<>();
        int intergeBit = maskBit / 8;
        int remainderBit = maskBit % 8;
        List<String> ipBitList = Arrays.asList(ip.split("\\."));

        // 需要保留的
        List<String> resultList = ipBitList.subList(0,intergeBit);
        // 最终结果
        List<String> finalResult = new ArrayList<>(resultList);
        if (remainderBit == 0){
            for (int i = resultList.size(); i<ipBitList.size(); i++){
                otherBits.add("0");
            }
            if (!otherBits.isEmpty()){
                finalResult.addAll(otherBits);
            }
        }else {
            // 需要转化的
            int remainBit = Integer.parseInt(ipBitList.subList(intergeBit,intergeBit + 1).get(0));
            if (resultList.size() < 3){
                for (int i =intergeBit+1; i < 4; i++){
                    otherBits.add("0");
                }
            }
            // 将remainBit转为二进制形式
            String binaryString = Integer.toBinaryString(remainBit);
            // 00101001
            String newString = String.format("%08d", Integer.parseInt(binaryString));
            // 00101
            String resultString = newString.substring(0,remainderBit);
            int  resultStringInteger = Integer.parseInt(resultString, 2);
            String leftMoveResultBinary = Integer.toBinaryString(resultStringInteger<<(8 - remainderBit));
            String leftMoveResultInteger = String.format("%08d", Integer.parseInt(leftMoveResultBinary));
            int  finRemainderInteger = Integer.parseInt(leftMoveResultInteger, 2);
            finalResult.add(String.valueOf(finRemainderInteger));
            if (!otherBits.isEmpty()){
                finalResult.addAll(otherBits);
            }
        }
        // 返回网段+子网掩码位数
        return CollUtil.join(finalResult, ".");
    }
}
